package com.ushine.web.security.utils;

import com.ushine.web.base.model.system.UserDO;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 功能描述:
 * 〈Security相关操作〉
 *
 * @author : yls
 * @date : 2022/3/11 16:18
 */
public class SecurityUtils {

    private SecurityUtils() {

    }

    /**
     * 功能描述:
     * 〈获取当前用户名〉
     *
     * @return : java.lang.String
     * @author : yls
     * @date : 2022/3/11 16:18
     */
    public static String getUsername() {
        String username = null;
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            }
        }
        return username;
    }

    /**
     * 功能描述
     * <获取用户信息>
     *
     * @return : org.springframework.security.core.userdetails.UserDetails
     * @author : yls
     * @date : 2021/7/22 15:14
     */
    public static UserDO getUser() {
        UserDO userDetails = null;
        Authentication authentication = getAuthentication();
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                userDetails = ((UserDO) principal);
            }
        }
        return userDetails;
    }

    /**
     * 功能描述:
     * 〈获取用户名〉
     *
     * @param authentication 认证信息
     * @return : java.lang.String
     * @author : yls
     * @date : 2022/3/11 16:18
     */
    public static String getUsername(Authentication authentication) {
        String username = null;
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            }
        }
        return username;
    }

    /**
     * 功能描述:
     * 〈获取当前登录信息〉
     *
     * @return : org.springframework.security.core.Authentication
     * @author : yls
     * @date : 2022/3/11 16:18
     */
    public static Authentication getAuthentication() {
        if (SecurityContextHolder.getContext() == null) {
            return null;
        }
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
